/**
 * 入职须知模板编辑页
 */
import React, { useMemo, useState } from 'react';
import { useRequest } from '@/hooks';
import { Spin } from 'antd';
import { withRouter } from 'umi';
import { PreviewEntryGuide } from '@/pages/TurnoverSetting/EntrySetting/components';
import useDictionary from '@/hooks/useDictionary';
import Store from 'store';
import { getGuideNoticeConfig } from '../services';
import styles from './index.less';

const EntryGuideNoticeSettingPreview = ({ location }) => {
    const { query } = location;
    const { id } = query;
    const [data, setData] = useState({});

    const { loading } = useRequest(() => getGuideNoticeConfig(id), {
        ready: !!id,
        formatResult: res => {
            if (res) {
                const { code } = res;
                if (code === 10000) {
                    setData(res.data);
                }
            }
            return undefined;
        }
    });

    const [paramOfEntryNoteList] = useDictionary('paramOfEntryNote');

    React.useEffect(() => {
        if (!id) {
            setData(Store.get('EntryGuideNoticeSettingMailContent'));
        }
    }, [id]);

    // 获取内容, 并替换掉参数占位符为默认内容
    const content = useMemo(() => {
        let html = data?.tplContent;
        if (html) {
            const arr = html.match(/\${[a-zA-Z]+}/g);
            if (arr && arr.length > 0 && paramOfEntryNoteList?.length) {
                arr.forEach(item => {
                    const field = item.replace('${', '').replace('}', '');
                    const fieldName = paramOfEntryNoteList.find(c => c.value === field)?.properties?.default || '';
                    html = html.replace(item, fieldName);
                });
            }
            console.log('===============================================>html', html);
            return html;
        }
        return '';
    }, [data, paramOfEntryNoteList]);

    return (
        <div className={styles.preview}>
            <PreviewEntryGuide>
                <Spin spinning={loading} style={{ width: '100%' }}>
                    {data?.tplContent && (
                        /* eslint-disable-next-line react/no-danger */
                        <div dangerouslySetInnerHTML={{ __html: content }} />
                    )}
                </Spin>
            </PreviewEntryGuide>
        </div>
    );
};

EntryGuideNoticeSettingPreview.displayName = 'EntryGuideNoticeSettingPreview';

export default React.memo(withRouter(EntryGuideNoticeSettingPreview));
